<?php

// +----------------------------------------------------------------------
// | 用户
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\v3;

use app\event\ucenter\User as UserEvent;
use app\pay\event\UserBalance as UserBalanceEvent;
use app\pay\event\UserBalanceCash as UserBalanceCashEvent;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\ucenter\UserCash as UserCashModel;
use think\Exception;
use think\facade\Db;
use wechat\mch\PayV3;
use wechat\official_account\Template as TemplateOfficial;
use app\model\ucenter\User as UserModel;

class Balance extends Common
{
    public function index()
    {

        if ($this->user) {
            $info['yesterday_profit'] = UserMoneyLogModel::where('money', '>', 0)
                ->where('user_id', $this->user['id'])
                ->whereTime('create_time', 'yesterday')
                ->where('type', 'in', [11, 12, 13, 14, 15, 16, 18, 20, 21, 66])->sum('money');
            $info['all_cash'] = -UserMoneyLogModel::where('user_id', $this->user['id'])
                ->where('type', 'in', [1])->sum('money');

            return $this->successAjax($info);
        } else {
            return $this->errorAjax('用户未登录');
        }

    }

    public function cash_log()
    {
        $status = $this->request->param('status', 1);
        $info = UserCashModel::where('user_id', $this->user['id'])->when($status, function ($query) use ($status) {
            // 满足条件后执行
            if ($status == 1) {
                $query->where('status', 1);
            } elseif ($status == 2) {
                $query->where('status', 0);
            } else {
                $query->where('status', 2);
            }
        })->order('create_time desc')->where('create_time', '>', '2024-09-01')->paginate();
        return $this->successAjax($info);
    }

    public function log()
    {
        $info = UserMoneyLogModel::where('user_id', $this->user['id'])->where('status', 5)->where('create_time', '>', '2024-09-01')->order('create_time desc')->paginate();
        return $this->successAjax($info);
    }

    // 首页
    public function cash()
    {
        if ($this->request->isPost()) {

            try {
                if (cache('cash_' . $this->user['id'])) {
                    throw new Exception('操作频繁，请稍后');
                }
                cache('cash_' . $this->user['id'], 1, 10);
                $param = $this->request->param();
                $minMoney = 10;
                if ($this->user['id'] != 16006 && $param['cash_money'] < $minMoney) {
                    throw new Exception('最低提现10元');
                }
                if ($param['cash_money'] > 10000) {
                    throw new Exception('提现超额');
                }
                $userMoney = $this->user['money'];
                if ($userMoney < $param['cash_money']) {
                    throw new Exception('账户余额不足');
                }

                if (UserEvent::get_effective_money($this->user['id']) == 0) {
                    throw new Exception('您的展业收益为0，需要有任意一笔展业收益');
                }
                if (!$this->user['realName']) {
                    throw new Exception('您还没有进行实名认证');
                }

                if (isset($param['channel']) && $param['channel'] == 'wxpay') {
                    $bank_type = 2;
                }else{
                    $bank_type = 1;
                }
                if ($bank_type == 1)
                {
                    if (empty($this->user['alipay_no']) && empty($param['alipay_no'])) {
                        throw new Exception('您还没有绑定支付宝');
                    }
                    $bank_no = $param['alipay_no'];
                }else{
                    $bank_no = $param['open_id'];
                }


                if ($this->user['id'] != 16006 && UserCashModel::where('user_id', $this->user['id'])->whereTime('create_time', 'today')->find()) {
                    throw new Exception('每天限制提现一次');
                }
                Db::startTrans();
                if ($this->user['free_balance'] > 0) {
                    if ($this->user['free_balance'] < $param['cash_money']) {
                        $fee = ($param['cash_money'] - $this->user['free_balance']) * 0.09 + 2;
                        Db::name('user')->where('id', $this->user['id'])->update(['free_balance' => 0]);
                    } else {
                        $fee = 0;
                        Db::name('user')->where('id', $this->user['id'])->update(['free_balance' => $this->user['free_balance'] - $param['cash_money']]);
                    }
                } else {
                    $fee = $param['cash_money'] * 0.09 + 2;
                }
                $data = [
                    'user_id' => $this->user['id'],
                    'agent_id' => $this->user['agent_id'],
                    'bank_no' => $bank_no,
                    'cash_money' => $param['cash_money'],
                    'before_money' => $userMoney,
                    'after_money' => $userMoney - $param['cash_money'],
                    'status' => 0,
                    'bank_type' => $bank_type,
                    'cash_charge' => $fee,
                    'real_cash' => $param['cash_money'] - $fee,
                    'real_name' => $this->user['idCardName']
                ];

                if ($param['cash_money'] <= 100) {
                     $data['billId'] = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                    if ($bank_type == 1)
                    {
                        if ($param['alipay_no'] != $this->user['alipay_no'])
                        {
                            UserModel::where('id',$this->user['id'])->update(['alipay_no' => $param['alipay_no']]);
                        }
                        //支付宝返款调用
                        $transferRes = alipay_transfer($data['billId'], round($data['real_cash'], 2), $data['bank_no'], $data['real_name']);

                        if ($transferRes['code'] !== 0) {
                            throw new Exception('提现失败！' . $transferRes['msg']);
                        }
                        $data['orderId'] = $transferRes['order_id'];
                        $data['status'] = 1;
                        $data['audit_time'] = time_format();

                    }else{
                        if ($this->user['id'] == 16006)
                        {

                            $config=[
                                'app_id'=>'wx7c83e79f78fdfa10',
                                'mch_id'=>'1697093647',
//                                'api_key'=>'qC04wNxXUFVv2eEItzWpdb8BSPMTkHln',
                                'key_path'=>root_path().'data/1697093647/apiclient_key.pem',
                                'cert_path'=> root_path().'data/1697093647/apiclient_cert.pem',
                            ];
//                            $userAuth,$config
                            $re = PayV3::transferv3($data['billId'],round($data['real_cash'], 2), $data['bank_no'], $data['real_name'],'云副业提现',$config);


                            // 微信申请
//                            $re = wechat_transfer($data['billId'], round($data['real_cash'], 2), $data['bank_no'], $data['real_name'],'云副业提现');
                            dump($re);exit();
                        }else{
                            throw new Exception('即将开放');
                        }
                    }
                }
                Db::name('user')->where('id', $this->user['id'])->setInc('cash_num');
//                $this->user['cash_num'] = $this->user['cash_num'] + 1;
//                $this->user->save();
                $info = UserCashModel::create($data);

                UserEvent::money(-$param['cash_money'], $this->user['id'], '余额提现', 1, $this->user['id']);
                Db::commit();
                if ($info['cash_money'] > 100) {
                    $oa_data = [
                        'thing3' => ['value' => $this->user['nickname'], 'color' => '#000000'],
                        'phone_number18' => ['value' => $this->user['username'], 'color' => '#000000'],
                        'character_string2' => ['value' => $info['sn'], 'color' => '#000000'],
                        'amount6' => ['value' => $param['cash_money'], 'color' => '#000000'],
                        //                'keyword1'=> ['value'=>$auth['idcard_name'], 'color'=>'#000000'],
                        //                'keyword2'=> ['value'=>time_format(), 'color'=>'#000000'],
                        'time13' => ['value' => time_format(), 'color' => '#000000'],
                    ];
                    $account['token'] = 'yunfuye1';
                    $account['encoding_aes_key'] = 'BkrUUPz9IgfERTRXmwiIf0RSir4ONBku64EufsZ9EE2';
                    $account['app_secret'] = 'cbdd44c7d119c8b4dd51b74c3030aa75';
                    $account['app_id'] = 'wxd4cc6bfc61b75cc5';
                    $oa = new TemplateOfficial();
                    $oa->initAccount($account);
                    // 微尘
                    //小花
                    $re = $oa->send('oAAIg6zwyPLf6jeOUBvWazwzA2qU', 'WsQr3fXxkekM039dy0rYtP_G2Zoqf5j_y66Rvw7RujA', $oa_data, '');
                    //张点成
//                    $re = $oa->send('oAAIg61CfAjbBmIPUojwc87FsQBA', 'WsQr3fXxkekM039dy0rYtP_G2Zoqf5j_y66Rvw7RujA', $oa_data, '');
                    // 微尘
//                    $re = $oa->send('oAAIg6w_C0wy7_rmcb3VahTohD6s', 'WsQr3fXxkekM039dy0rYtP_G2Zoqf5j_y66Rvw7RujA', $oa_data, '');
                    //张琦
                    $re = $oa->send('oAAIg622danHy6GAlzK5v4uZsou0', 'WsQr3fXxkekM039dy0rYtP_G2Zoqf5j_y66Rvw7RujA', $oa_data, '');
                }
                return $this->successAjax($info);
            } catch (Exception $exception) {
                Db::rollback();
                return $this->errorAjax($exception->getMessage());
            }

        } else {
            $info['tips'][] = '每天仅可提现1笔';
            $info['tips'][] = '需要有任意一笔展业收益';
            $info['tips'][] = '单次提现需要满10元';
            $info['tips'][] = '提现金额100元以内秒到，超出100元次工作日到账。';
            $info['tips'][] = '提现需代扣税点9%和单笔提现费2元/笔。';
            $info['tips'][] = '姓名与提现账号必须一致';
            if ($this->user['free_balance']) {
                $info['tips'][] = '您当前现有' . $this->user['free_balance'] . '元的免扣税点额度';
            }
            // 提示限制
            $info['show'] = [];
            if ($this->user['money'] < 10) {
                $info['show'][] = '单次提现需要满10元，您的余额不足';
            }

            if (UserEvent::get_effective_money($this->user['id']) == 0) {
                $info['show'][] = '您的展业收益为0，需要有任意一笔展业收益';
            }
            if (!$this->user['realName']) {
                $info['show'][] = '您还没有进行实名认证';
            }
            if (empty($this->user['alipay_no']) && empty($param['alipay_no'])) {
                $info['show'][] = '您还没有绑定支付宝';
            }

            if (UserCashModel::where('user_id', $this->user['id'])->whereTime('create_time', 'today')->find()) {
                $info['show'][] = '每天限制提现一次';
            }
            if (count($info['show']) > 0) {
                $info['show_tips'] = '您的账号有如下限制，请完成后再提现：<br>';
                foreach ($info['show'] as $index => $item) {
                    $info['show_tips'] .= (($index + 1) . '、' . $item) . '<br>';
                }
            }
            $info['cash_channel']['alipay_no'] = $this->user['alipay_no'];
//            $info['cash_channel']['wechat_info'] = '';
            $info['cash_channel']['wechat_info'] = $this->user->oauths()->where('channel','weixin')->find();
            return $this->successAjax($info);
        }


    }

    public function history()
    {

        $status = $this->request->param('status/d', 0);
        $limit = input('limit/d', 15);
        switch ($status) {
            case 1:
                $money = '>';
                break;
            case 2:
                $money = '<';
                break;
            default:
                $money = false;
                break;
        }
        $data['lists'] = UserMoneyLogModel::with('from')
            ->where('user_id', $this->user['id'])
            ->append(['type_name', 'channel', 'logo', 'from_info'])
            ->when($money, function ($query) use ($money) {
                $query->where('money', $money, 0);
            })
            ->where('create_time', '>', '2024-09-01')
            ->order('create_time DESC')
            ->paginate($limit);
        return $this->successAjax($data);
    }


}
